<template>
  <div class="book-menu">
    <div class="book-menu-search" >
      <button class="btn" @click="search">搜一下</button>
      <input type="text" id="bookName">
    </div>
    <div class="book-menu-list">
      <div class="book-menu-item" v-for="item in bookList" :key="item.id" @click="readBook(item.id)">
        <img :src="item.image">
        <div class="book-menu-item-desc"> 
          <span>书名：{{item.name}}</span>
          <span>作者：{{item.author}}</span>
          <span>字数：{{item.totalWords}}</span>
          <span>点赞：{{item.totalStart}}</span>
        </div>
      </div>
    </div>
    <div class="book-menu-pagenation">
      <button class="btn" @click="next"> 下一页 </button>
      <button class="btn" @click="pre"> 上一页 </button>
    </div>
  </div>
</template>

<script>

import {getBookList} from '@/api/book.js'

export default {
  data(){
    return {
      page: 1,
      pageSize: 10,
      name: '',
      bookList:[]
    }
  },
  mounted() {
    this.listBook()
  },
  methods: {
    readBook(bookId) {
      this.$router.push('/book-reader/' + bookId)
    },
    search(bookName) {
      this.name = bookName
      this.listBook()
    },
    next() {
      this.page += 1
      this.listBook()
    },
    pre() {
      if (this.page == 1) {
        alert("已经是第一页了")
        return
      }
      this.page -= 1
      this.listBook()
    },
    listBook(){
      getBookList(this.page, this.pageSize, this.name).then( (response) => {
        if (response.status != 200) {
          alert(response.statusText)
          return
        } else {
          if (response.data.bookList.len == 0) {
            alert("已经是最后一页了")
            this.page -= 1
            return
          }
          this.bookList = response.data.bookList
        }
      })
    }
    
  }
}
</script>

<style>

.book-menu-search {
  display: flex;
  flex-direction: row-reverse;
}
.book-menu-pagenation {
  display: flex;
  flex-direction: row-reverse;
}
.book-menu-list {
  grid-template-columns: repeat(2, 49%);
  display: grid;
  grid-gap: 5px 2%;
  padding: 2% 0;
}
.book-menu-item {
  display: flex;
  background-color: floralwhite;
}
.book-menu-item img {
  width: 40%;
}
.book-menu-item-desc {
  display: grid;
  font-size: xx-small;
}
.book-menu-item-desc span{
  height: auto;
  word-wrap: break-word; /*强制换行*/
  overflow: hidden; /*超出隐藏*/
  text-overflow: ellipsis;/*隐藏后添加省略号*/
  white-space: nowrap;/*强制不换行*/
}
.btn {
  background: transparent; /* 清除背景色 */
  border: 1px solid;
  border-radius: 5px; /* 给边框添加圆角 */
  color: black;
  text-align: center;
  text-decoration: none;
  display: inline-block;
  cursor: pointer;
  margin-left: 10px;
}
</style>